import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

/**
 * Represents a personal Reclist unique to a specific user.
 * 
 */
public class PersonalRecList {
	private File personalRecListFile;
	private ArrayList<PMovieRec> pRecList;

	/**
	 * Constructor
	 * 
	 * @param fileLocation
	 *            File pathname of saved PMovieRec, if it exists
	 * @param userName
	 *            User which owns this specific PersonalRecList
	 */
	public PersonalRecList(String fileLocation, String userName) {
		personalRecListFile = new File(fileLocation + "\\" + userName + ".dat");
		pRecList = new ArrayList<PMovieRec>();
		load();
	}

	/**
	 * Loads a specific PersonalRecList from file.
	 */
	public void load() 
	{
		try 
		{
			if (!personalRecListFile.exists()) 
			{
				personalRecListFile.createNewFile();
				return;
			}
		} catch (IOException exception) {
			System.out.println("There was an error creating a PersonalMovieRecList file.");
			System.exit(0);
		}

		try 
		{
			BufferedReader br = new BufferedReader(new FileReader(personalRecListFile));
			String line = "";

			while ((line = br.readLine()) != null) {
				String[] pMovieRecParams = line.split("#");
				pRecList.add(new PMovieRec(pMovieRecParams[0], Integer.parseInt(pMovieRecParams[1])));
			}
			br.close();
		} catch (FileNotFoundException exception) {
			System.out.println("Somehow the personalRecListFile wasn't found, even though there was a check several lines ago.");
			System.exit(0);
		} catch (IOException exception) {
			System.out.println("There was error reading the personalRecList file.");
			System.exit(0);
		}
	}

	/**
	 * Updates the list to file
	 * 
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void update() throws FileNotFoundException, IOException {
		PrintWriter pw = new PrintWriter(personalRecListFile);
		for (PMovieRec pMovieRec : pRecList){
			pw.println(pMovieRec.getName() + "#" + pMovieRec.getReleaseYear());
		}
		pw.close();
	}

	/**
	 * Adds a movie to the PRecList
	 * 
	 * @param newMovie
	 *            the movie to be added
	 */
	public void add(PMovieRec newMovie) throws DuplicateRecException
	{
		for (PMovieRec movie : pRecList)
		{
			if (movie.equals(newMovie))
			{
				throw new DuplicateRecException();
			}
		}
		pRecList.add(newMovie);
		Collections.sort(pRecList);
	}

	/**
	 * Prints the contents of the PersonalRecList.
	 * @throws EmptyListException Thrown if PersonalRecList is an empty list.
	 */
	public void display() throws EmptyListException
	{
		if (pRecList.size() == 0)
			throw new EmptyListException();
		for (PMovieRec b : pRecList) {
			System.out.println(b.toString());
		}
	}
}
